package com.fbooks.utils;
import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @Author: LuoRunFeng
 * @e-mail: 475403147@qq.com
 * @Time: 2020/3/21 17:09
 * @Version 1.0
 */
public class fastdfsUtils {

    private static String tracker="";
    private static TrackerClient trackerClient=null;
    private static TrackerServer trackerServer=null;
    private static StorageClient storageClient=null;


    static {
        //获得配置文件路径
        tracker= fastdfsUtils.class.getResource("/fdfs_client.conf").getPath();
        //获取到相关配置，然后初始化
        try {
            ClientGlobal.init(tracker);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
        //创建对象
        trackerClient=new TrackerClient(ClientGlobal.g_tracker_group);

        //获得trackerServer实例
        try {
            trackerServer = trackerClient.getTrackerServer();
        } catch (IOException e) {
            e.printStackTrace();
        }

        storageClient=new StorageClient(trackerServer,null);
    }



    /**
     * 图片上传
     * @param multipartFile
     * @return
     * @throws IOException
     * @throws MyException
     */
    public static String uploadImage(MultipartFile multipartFile){

        String imgUrl="http://111.229.163.136";

        //获取上传对象的二进制文件
        byte[] bytes= new byte[0];
        try {
            bytes = multipartFile.getBytes();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取文件名+扩展名
        String originalFilename=multipartFile.getOriginalFilename();
        //找到文件最后一个点的位置
        Integer LastIndex=originalFilename.lastIndexOf(".");
        //将最后的后缀分离,从而获取到后缀名
        String extName=originalFilename.substring(LastIndex);

        //获取到返回来的信息  group 以及位置
        try {
            String[] uploadInfos = storageClient.upload_file(bytes, extName, null);
            for (String uploadInfo : uploadInfos) {
                imgUrl+="/"+uploadInfo;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return imgUrl;
    }
}
